/**
 * Electron 恢复引擎适配器
 * 使用 Electron API 替代直接的 Node.js 文件系统调用
 */

import type { 
  RecoveryTask, 
  RecoveryResult, 
  BatchRecoveryResult, 
  RecoveryOptions
} from '../types/basic'

export class ElectronRecoveryEngineImpl {
  private maxConcurrentTasks: number

  constructor(maxConcurrentTasks: number = 3) {
    this.maxConcurrentTasks = maxConcurrentTasks
  }

  /**
   * 恢复单个文件
   */
  async recoverFile(task: RecoveryTask, options: Partial<RecoveryOptions> = {}): Promise<RecoveryResult> {
    try {
      // 构建源文件路径（从历史版本中）
      const sourcePath = this.buildHistoryFilePath(task.versionId, task.fileId)
      
      // 确定目标路径
      const targetPath = task.targetPath
      const resolvedTarget = window.pathAPI.resolve(targetPath)
      
      // 检查覆盖设置
      if (!options.overwrite && await this.fileExists(resolvedTarget)) {
        throw new Error('Target file exists and overwrite is disabled')
      }
      
      // 执行恢复操作
      await this.copyFile(sourcePath, resolvedTarget)
      
      // 读取文件大小
      const fileResult = await window.electronAPI.readFile(resolvedTarget)
      const bytesWritten = fileResult.content ? fileResult.content.length : 0
      
      return {
        success: true,
        targetPath: resolvedTarget,
        bytesWritten
      }
    } catch (error) {
      return {
        success: false,
        targetPath: task.targetPath,
        error: error instanceof Error ? error.message : String(error),
        bytesWritten: 0
      }
    }
  }

  /**
   * 批量恢复文件
   */
  async batchRecover(tasks: RecoveryTask[], options: Partial<RecoveryOptions> = {}): Promise<BatchRecoveryResult> {
    const startTime = Date.now()
    const successful: RecoveryResult[] = []
    const failed: RecoveryResult[] = []
    
    // 使用并发控制处理批量任务
    const chunks = this.chunkArray(tasks, this.maxConcurrentTasks)
    
    for (const chunk of chunks) {
      const promises = chunk.map(task => this.recoverFile(task, options))
      const results = await Promise.allSettled(promises)
      
      results.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          if (result.value.success) {
            successful.push(result.value)
          } else {
            failed.push(result.value)
          }
        } else {
          // Promise 被拒绝
          failed.push({
            success: false,
            targetPath: chunk[index].targetPath,
            error: result.reason instanceof Error ? result.reason.message : String(result.reason),
            bytesWritten: 0
          })
        }
      })
    }
    
    const endTime = Date.now()
    
    return {
      successful,
      failed,
      totalCount: tasks.length,
      duration: endTime - startTime
    }
  }

  /**
   * 检查文件是否存在
   */
  private async fileExists(filePath: string): Promise<boolean> {
    try {
      const result = await window.electronAPI.readFile(filePath)
      return result.success
    } catch {
      return false
    }
  }

  /**
   * 复制文件
   */
  private async copyFile(sourcePath: string, targetPath: string): Promise<void> {
    const result = await window.electronAPI.copyFile(sourcePath, targetPath)
    
    if (!result.success) {
      throw new Error(result.error || 'Copy operation failed')
    }
  }

  /**
   * 构建历史文件路径
   */
  private buildHistoryFilePath(versionId: string, fileId: string): string {
    // 这里需要根据实际的历史文件存储结构来实现
    // 简化实现：假设历史文件存储在 History/{versionId}/{fileId}
    return window.pathAPI.join('History', versionId, fileId)
  }

  /**
   * 将数组分块以控制并发
   */
  private chunkArray<T>(array: T[], chunkSize: number): T[][] {
    const chunks: T[][] = []
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize))
    }
    return chunks
  }


}

// 检查是否在 Electron 环境中
const isElectron = typeof window !== 'undefined' && window.electronAPI

// 导出适当的实例
export const recoveryEngine = isElectron 
  ? new ElectronRecoveryEngineImpl()
  : null // 在非 Electron 环境中返回 null